package com.sunseaypw.springboot;

import java.io.IOException;

import javax.annotation.PostConstruct;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
// 启动自动配置，但排除指定的自动配置:
@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Bean
    ConnectionFactory getConnectionFactory(
        @Value("${spring.rabbitmq.host}") String host
        ,@Value("${spring.rabbitmq.host}") String rabbitHost
        ,@Value("${spring.rabbitmq.port}") int rabbitPort
        ,@Value("${spring.rabbitmq.virtual-host}") String rabbitVHost
        ,@Value("${spring.rabbitmq.username}") String rabbitUsername
        ,@Value("${spring.rabbitmq.password}") String rabbitPassword
    ){        
        var factory=new ConnectionFactory();
            factory.setHost(rabbitHost);
            factory.setPort(rabbitPort);                
            factory.setVirtualHost(rabbitVHost);
            factory.setUsername(rabbitUsername);
            factory.setPassword(rabbitPassword);
        return factory;
    }

    @RestController
    public static class MQConsumer{     
        @Autowired
        ConnectionFactory factory;

        @PostConstruct
        public void init(){
            //独立非boot amqp模式，切记不要混用！！！
            var t=new Thread(()->{                
                try(
                    var conn=factory.newConnection();
                    var channel=conn.createChannel();
                ){
                    var queneName="my-quene";
                    channel.queueDeclareNoWait(queneName, true,false,false,null);
                    while(true){
                        channel.basicConsume(queneName,new DefaultConsumer(channel){
                            @Override
                            public void handleDelivery(String consumerTag,Envelope envelope,
                                AMQP.BasicProperties properties, byte[] body) throws IOException {
                                String routingKey = envelope.getRoutingKey();
                                String contentType = properties.getContentType();
                                System.out.println("消息的路由键：" + routingKey);
                                System.out.println("消息的内容类型：" + contentType);
                                long deliveryTag = envelope.getDeliveryTag();
                                //确认消息
                                channel.basicAck(deliveryTag, false);
                                System.out.println("消息的消息体内容：");
                                String bodyStr = new String(body, "UTF-8");
                                System.out.println(bodyStr);
                            }
                        });                
                    }
                }catch(Exception ex){
                    ex.printStackTrace();
                }
            });
            //t.start();            
        }
    
        @GetMapping("/product/{msg}")
        public String product(@PathVariable("msg") String msg){
            try(
                var conn=factory.newConnection();
                var channel=conn.createChannel();
            ){
                var queneName="my-quene";
                var exchangeName="my-direct";
                channel.exchangeDeclare("my-direct", BuiltinExchangeType.DIRECT);   
                channel.exchangeDeclare("my-direct", BuiltinExchangeType.DIRECT);                
                channel.queueBind(queneName, exchangeName, "rk-001");
                channel.queueBind(queneName, exchangeName, "rk-001");
                //var msg="中国人民万岁！！！";
                channel.basicPublish("", "my-quene", null, msg.getBytes());
                channel.basicPublish("", "rk-001", null, msg.getBytes());
            }catch(Exception ex){
                return ex.getMessage();
            }
            return "发送成功";
        }

        @GetMapping("/")
        public String hello(){
            return "hello world";
        }    
        
        @Autowired
        private MsgProductor producer;
        @GetMapping("/sendmsg/{key}/{msg}")
        public String sendmsg(@PathVariable("key") String key,@PathVariable("msg") String msg){  
            switch(key){
                case "1":
                    producer.sendDirectMsg("cord", msg);
                    break;
                case "2":
                    producer.sendExchangeMsg("topic-exchange","org.cord.test", msg);
                    break;
                case "3":
                    producer.sendExchangeMsg("fanout-exchange", "abcdefg", msg);
                    break;
            }   
            return "已发送";
        }   

        @RabbitListener(queues = {"cord"})
        public void getMsg(String msg){
            System.out.println(msg);
        }     
    }
}